/**
 * 虚拟滚动性能测试工具
 */

import { KafkaMessage } from '@/stores/kafkaStore'

// 性能测试配置
interface PerformanceTestConfig {
  messageCount: number
  batchSize: number
  testDuration: number // 秒
  enableLogging: boolean
}

// 性能指标
interface PerformanceMetrics {
  renderTime: number
  scrollFPS: number
  memoryUsage: number
  searchTime: number
  filterTime: number
}

// 生成测试数据
export function generateTestMessages(count: number): KafkaMessage[] {
  const messages: KafkaMessage[] = []
  const topics = ['user-events', 'order-events', 'payment-events', 'notification-events']
  const partitions = [0, 1, 2, 3, 4]
  
  for (let i = 0; i < count; i++) {
    const topic = topics[i % topics.length]
    const partition = partitions[i % partitions.length]
    
    messages.push({
      topic,
      partition,
      offset: i,
      timestamp: Date.now() - (count - i) * 1000, // 递增时间戳
      key: `key_${i}`,
      value: {
        id: i,
        userId: `user_${Math.floor(i / 10)}`,
        action: ['login', 'logout', 'purchase', 'view', 'click'][i % 5],
        timestamp: new Date().toISOString(),
        metadata: {
          ip: `192.168.1.${(i % 254) + 1}`,
          userAgent: 'Mozilla/5.0 (compatible; TestBot/1.0)',
          sessionId: `session_${Math.floor(i / 100)}`,
          data: `This is test message number ${i} with some additional content to make it more realistic. `.repeat(Math.floor(i % 3) + 1)
        }
      },
      headers: {
        'content-type': 'application/json',
        'source': 'test-generator',
        'version': '1.0'
      }
    })
  }
  
  return messages
}

// 性能测试类
export class VirtualScrollPerformanceTest {
  private config: PerformanceTestConfig
  private metrics: PerformanceMetrics
  private startTime: number = 0
  private frameCount: number = 0
  private lastFrameTime: number = 0

  constructor(config: Partial<PerformanceTestConfig> = {}) {
    this.config = {
      messageCount: 10000,
      batchSize: 100,
      testDuration: 10,
      enableLogging: true,
      ...config
    }
    
    this.metrics = {
      renderTime: 0,
      scrollFPS: 0,
      memoryUsage: 0,
      searchTime: 0,
      filterTime: 0
    }
  }

  // 测试渲染性能
  async testRenderPerformance(messages: KafkaMessage[]): Promise<number> {
    const startTime = performance.now()
    
    // 模拟渲染过程
    const renderStart = performance.now()
    
    // 模拟DOM操作
    const container = document.createElement('div')
    container.style.height = '600px'
    container.style.overflow = 'auto'
    
    // 创建虚拟列表项
    for (let i = 0; i < Math.min(20, messages.length); i++) {
      const item = document.createElement('div')
      item.style.height = '60px'
      item.textContent = JSON.stringify(messages[i])
      container.appendChild(item)
    }
    
    document.body.appendChild(container)
    
    // 强制重排
    container.offsetHeight
    
    const renderTime = performance.now() - renderStart
    
    // 清理
    document.body.removeChild(container)
    
    this.metrics.renderTime = renderTime
    
    if (this.config.enableLogging) {
      console.log(`渲染性能测试: ${renderTime.toFixed(2)}ms`)
    }
    
    return renderTime
  }

  // 测试滚动性能
  testScrollPerformance(): Promise<number> {
    return new Promise((resolve) => {
      const container = document.createElement('div')
      container.style.height = '600px'
      container.style.overflow = 'auto'
      
      // 创建大量内容
      const content = document.createElement('div')
      content.style.height = '100000px'
      container.appendChild(content)
      document.body.appendChild(container)
      
      let frameCount = 0
      let lastTime = performance.now()
      const startTime = lastTime
      
      const measureFPS = () => {
        const currentTime = performance.now()
        frameCount++
        
        if (currentTime - startTime >= 1000) {
          const fps = frameCount / ((currentTime - startTime) / 1000)
          this.metrics.scrollFPS = fps
          
          document.body.removeChild(container)
          
          if (this.config.enableLogging) {
            console.log(`滚动FPS: ${fps.toFixed(2)}`)
          }
          
          resolve(fps)
          return
        }
        
        // 模拟滚动
        container.scrollTop += 10
        requestAnimationFrame(measureFPS)
      }
      
      requestAnimationFrame(measureFPS)
    })
  }

  // 测试内存使用
  testMemoryUsage(): number {
    if ('memory' in performance) {
      const memory = (performance as any).memory
      const usedJSHeapSize = memory.usedJSHeapSize / 1024 / 1024 // MB
      this.metrics.memoryUsage = usedJSHeapSize
      
      if (this.config.enableLogging) {
        console.log(`内存使用: ${usedJSHeapSize.toFixed(2)}MB`)
      }
      
      return usedJSHeapSize
    }
    
    return 0
  }

  // 测试搜索性能
  async testSearchPerformance(messages: KafkaMessage[], query: string): Promise<number> {
    const startTime = performance.now()
    
    const results = messages.filter(message => {
      const valueStr = JSON.stringify(message.value).toLowerCase()
      const keyStr = (message.key || '').toLowerCase()
      const queryLower = query.toLowerCase()
      
      return valueStr.includes(queryLower) || keyStr.includes(queryLower)
    })
    
    const searchTime = performance.now() - startTime
    this.metrics.searchTime = searchTime
    
    if (this.config.enableLogging) {
      console.log(`搜索性能: ${searchTime.toFixed(2)}ms, 结果: ${results.length}条`)
    }
    
    return searchTime
  }

  // 测试过滤性能
  async testFilterPerformance(messages: KafkaMessage[]): Promise<number> {
    const startTime = performance.now()
    
    // 模拟复杂过滤条件
    const filtered = messages.filter(message => {
      // 时间范围过滤
      const timeCheck = message.timestamp && message.timestamp > Date.now() - 24 * 60 * 60 * 1000
      
      // 分区过滤
      const partitionCheck = message.partition >= 0 && message.partition <= 2
      
      // 内容过滤
      const contentCheck = JSON.stringify(message.value).length > 100
      
      return timeCheck && partitionCheck && contentCheck
    })
    
    const filterTime = performance.now() - startTime
    this.metrics.filterTime = filterTime
    
    if (this.config.enableLogging) {
      console.log(`过滤性能: ${filterTime.toFixed(2)}ms, 结果: ${filtered.length}条`)
    }
    
    return filterTime
  }

  // 运行完整性能测试
  async runFullTest(): Promise<PerformanceMetrics> {
    console.log('🚀 开始虚拟滚动性能测试...')
    
    // 生成测试数据
    console.log(`📊 生成 ${this.config.messageCount} 条测试消息...`)
    const messages = generateTestMessages(this.config.messageCount)
    
    // 测试渲染性能
    console.log('🎨 测试渲染性能...')
    await this.testRenderPerformance(messages)
    
    // 测试滚动性能
    console.log('📜 测试滚动性能...')
    await this.testScrollPerformance()
    
    // 测试内存使用
    console.log('💾 测试内存使用...')
    this.testMemoryUsage()
    
    // 测试搜索性能
    console.log('🔍 测试搜索性能...')
    await this.testSearchPerformance(messages, 'user_100')
    
    // 测试过滤性能
    console.log('🔧 测试过滤性能...')
    await this.testFilterPerformance(messages)
    
    console.log('✅ 性能测试完成!')
    this.printResults()
    
    return this.metrics
  }

  // 打印测试结果
  private printResults(): void {
    console.log('\n📈 性能测试结果:')
    console.log('================')
    console.log(`渲染时间: ${this.metrics.renderTime.toFixed(2)}ms`)
    console.log(`滚动FPS: ${this.metrics.scrollFPS.toFixed(2)}`)
    console.log(`内存使用: ${this.metrics.memoryUsage.toFixed(2)}MB`)
    console.log(`搜索时间: ${this.metrics.searchTime.toFixed(2)}ms`)
    console.log(`过滤时间: ${this.metrics.filterTime.toFixed(2)}ms`)
    
    // 性能评级
    console.log('\n🏆 性能评级:')
    console.log('============')
    console.log(`渲染性能: ${this.getRating(this.metrics.renderTime, [50, 100, 200])}`)
    console.log(`滚动性能: ${this.getRating(60 - this.metrics.scrollFPS, [5, 15, 30])}`)
    console.log(`内存效率: ${this.getRating(this.metrics.memoryUsage, [50, 100, 200])}`)
    console.log(`搜索效率: ${this.getRating(this.metrics.searchTime, [100, 500, 1000])}`)
    console.log(`过滤效率: ${this.getRating(this.metrics.filterTime, [50, 200, 500])}`)
  }

  private getRating(value: number, thresholds: [number, number, number]): string {
    if (value <= thresholds[0]) return '🟢 优秀'
    if (value <= thresholds[1]) return '🟡 良好'
    if (value <= thresholds[2]) return '🟠 一般'
    return '🔴 需要优化'
  }

  // 获取测试结果
  getMetrics(): PerformanceMetrics {
    return { ...this.metrics }
  }
}

// 导出便捷函数
export async function runQuickPerformanceTest(messageCount: number = 1000): Promise<PerformanceMetrics> {
  const test = new VirtualScrollPerformanceTest({ messageCount, enableLogging: true })
  return await test.runFullTest()
}

// 性能监控Hook
export function usePerformanceMonitor() {
  const [metrics, setMetrics] = React.useState<PerformanceMetrics | null>(null)
  const [isRunning, setIsRunning] = React.useState(false)
  
  const runTest = async (messageCount: number = 1000) => {
    setIsRunning(true)
    try {
      const result = await runQuickPerformanceTest(messageCount)
      setMetrics(result)
    } finally {
      setIsRunning(false)
    }
  }
  
  return { metrics, isRunning, runTest }
}
